package com.gensdai.leliang.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.zfb.PayResult;
import com.mock.alipay.Callback;
import com.mock.alipay.PasswordKeypad;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/6/1.
 */

public class Recharge extends BaseActivityNoAbs implements View.OnClickListener {

    @BindView(R.id.ui_title)
    TextView uiTitle;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.please_recharge_monry)
    EditText pleaseRechargeMonry;
    @BindView(R.id.affirm_recharge)
    TextView affirmRecharge;
    @BindView(R.id.have_money)
    TextView haveMoney;

    private Upload up;

    private static final int SDK_PAY_FLAG = 1;
    private static final int GET_DATA = 2;

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult(
                            (Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Log.e("my_wallet", "resultInfo:" + resultInfo);
                    Log.e("my_wallet", "resultStatus:" + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(Recharge.this, "充值成功",
                                Toast.LENGTH_SHORT).show();
                        Recharge.this.finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(Recharge.this, "充值失败",
                                Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case GET_DATA:
                    up.dismiss();
//                    if (new json_base().GOOD((String) msg.obj)) {
                    try {
                        usezfb(new JSONObject((String) msg.obj).getString("data"));
                        Log.e("my_wallet", new JSONObject((String) msg.obj).getString("data"));
//                        usezfb();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
//                    } else {
//                        Toast.makeText(my_wallet.this, , Toast.LENGTH_LONG).show();
//                    }

                    break;
                default:
                    up.dismiss();
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recharge);
        ButterKnife.bind(this);
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        uiTitle.setText(getString(R.string.recharge));
        haveMoney.setText(String.format(getString(R.string.can_use_monry), getIntent().getStringExtra("money")));
        up = new Upload(this);
        back.setOnClickListener(this);
        affirmRecharge.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                this.finish();
                break;
            case R.id.affirm_recharge:
                if (pleaseRechargeMonry.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "充值金额不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                PayRequest2Str();
                break;
            default:
                break;
        }
    }

    private void usezfb(final String orderInfo) {
//    private void usezfb() {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(Recharge.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void PayRequest2Str() {
        //获取edit的值后请求

        String chongPrice = pleaseRechargeMonry.getText().toString().trim(); // 充值金额
        if (Double.parseDouble(chongPrice) < 0) {
            Toast.makeText(this, getString(R.string.error_recharge_monrey), Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> loginParams = new HashMap<>();
//        loginParams.put("userId", "000000");
        loginParams.put("userId", getSharedPreferences("User", MODE_PRIVATE).getString("user_id", ""));
        loginParams.put("chongPrice", chongPrice);
        toStr(loginParams);
    }

    /**
     * 获取订单信息
     */
    private void toStr(Map<String, String> data) {
        up.show();
        ApiService.getInstance().PayRequestStr(data)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = GET_DATA;
                        msg.obj = s;
                        mHandler.sendMessage(msg);

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        up.dismiss();
                        //异常处理
//                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }
}
